package com.zwj.batch.config.test;

import org.springframework.batch.core.Job;
import org.springframework.batch.core.Step;
import org.springframework.batch.core.configuration.annotation.JobBuilderFactory;
import org.springframework.batch.core.configuration.annotation.StepBuilderFactory;
import org.springframework.batch.core.launch.support.RunIdIncrementer;
import org.springframework.batch.item.ItemProcessor;
import org.springframework.batch.item.ItemReader;
import org.springframework.batch.item.ItemWriter;
import org.springframework.batch.item.NonTransientResourceException;
import org.springframework.batch.item.ParseException;
import org.springframework.batch.item.UnexpectedInputException;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.annotation.Resource;
import java.util.List;

/**
 * @author 张文接
 * @version 1.0
 * @createTime 2023-05-28 20:27:52
 */
//@Configuration
public class BatchConfig09 {

    //job构造工厂
    @Resource
    private JobBuilderFactory jobBuilderFactory;
    //step构造工厂
    @Resource
    private StepBuilderFactory stepBuilderFactory;

    @Bean
    public Job job() {
        return jobBuilderFactory
                .get("step-chunk-tasklet-job")
                .incrementer(new RunIdIncrementer())
                .start(step1())
                .build();
    }

    @Bean
    public Step step1() {
        return stepBuilderFactory
                .get("step1")
                .chunk(3)//每执行读取、处理操作3次，才会执行写操作1次
                .reader(itemReader())//读
                .processor(itemProcessor())//处理
                .writer(itemWriter())//写
                .build();
    }


    @Bean
    public ItemReader itemReader() {
        /**
         * 读操作
         */
        return new ItemReader() {
            @Override
            public Object read() throws Exception, UnexpectedInputException, ParseException, NonTransientResourceException {
                System.out.println("-------------read------------");
                return "read-ret";
            }
        };
    }

    @Bean
    public ItemProcessor itemProcessor() {
        return new ItemProcessor() {
            /**
             * 处理数据
             * @param item 需要处理的item
             * @return 处理后的item
             * @throws Exception
             */
            @Override
            public Object process(Object item) throws Exception {
                System.out.println("-------------process------------>" + item);
                return "process-ret->" + item;
            }
        };
    }

    @Bean
    public ItemWriter itemWriter() {
        /**
         * 对list进行写操作
         */
        return new ItemWriter() {
            @Override
            public void write(List list) throws Exception {
                System.out.println(list);
            }
        };
    }
}
